package com.jilijili.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jilijili.enums.Sex;
import com.jilijili.enums.UserInfoModifyType;
import com.jilijili.enums.YesOrNo;
import com.jilijili.exceptions.GraceException;
import com.jilijili.grace.result.ResponseStatusEnum;
import com.jilijili.mapper.UsersMapper;
import com.jilijili.pojo.Users;
import com.jilijili.pojo.bo.UsersUpdateBo;
import com.jilijili.service.UsersService;
import com.jilijili.utils.DateUtil;
import com.jilijili.utils.DesensitizationUtil;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author admin
 * @description 针对表【users(用户表)】的数据库操作Service实现
 * @createDate 2022-03-12 07:11:29
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
        implements UsersService {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private Sid sid;


    // 更新|修改 用户,查询并且返回用户 2.0
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public Users updateUserInfo(UsersUpdateBo usersUpdateBo, Integer type) {
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //TODO [1] 前置判断
        // [1.1] 昵称不能出现重复的
        if (type.equals(UserInfoModifyType.NICKNAME.type)) {
            Users users = this.usersMapper.selectOne(lambdaQueryWrapper
                    .eq(true, Users::getNickname, usersUpdateBo.getNickname()));
            //TODO [1.2] 用户不为空,昵称已经被占用
            lambdaQueryWrapper.clear();
            if (!ObjectUtils.isEmpty(users)) {
                GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_NICKNAME_EXIST_ERROR);
            }

        }

        //TODO [2] 产品号不能出现重复
        if (type.equals(UserInfoModifyType.IMOOCUNM.type)) {
            Users users = this.usersMapper.selectOne(lambdaQueryWrapper
                    .eq(true, Users::getImoocNum, usersUpdateBo.getImoocNum()));
            lambdaQueryWrapper.clear();
            //TODO [2.1] 用户不为空,慕课号已经被占用
            if (!ObjectUtils.isEmpty(users)) {
                GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_IMOOCNUM_EXIST_ERROR);
            }
            //TODO [2.2] 查询产品号是否可以被修改
            Users tempUsers = this.usersMapper.selectById(usersUpdateBo.getId());
            if (tempUsers.getCanImoocNumBeUpdated().equals(YesOrNo.NO.type)) {
                GraceException.display(ResponseStatusEnum.USER_INFO_CANT_UPDATED_IMOOCNUM_ERROR);
            }

            //TODO [2.3] 查询产品号设置为不可修改状态 0
            usersUpdateBo.setCanImoocNumBeUpdated(YesOrNo.NO.type);
        }
        return this.updateUserInfo(usersUpdateBo);
    }

    // 更新|修改 用户,查询并且返回用户
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public Users updateUserInfo(UsersUpdateBo usersUpdateBo) {
        Users pendingUser = UsersUpdateBo.convertUsers(usersUpdateBo);

        int result = usersMapper.updateById(pendingUser);
        if (result != 1) {
            GraceException.display(ResponseStatusEnum.USER_STATUS_ERROR);
        }

        return this.getUser(usersUpdateBo.getId());
    }

    // 通过id 查询用户
    @Override
    public Users getUser(String userId) {
        return usersMapper.selectById(userId);
    }

    // 通过手机号判断使用后是否存在
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public Users queryMobileIsExist(String mobile) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("mobile", mobile);
        return usersMapper.selectOne(usersQueryWrapper);
    }

    // 创建用户对象
    @Override
    public Users creteUser(String mobile) {
        Users newUser = new Users();
        // 随机的头像
        String Face = "https://api.dzzui.com/api/avatar";
        // 没有注册的用户初始化
        newUser.setId(this.sid.nextShort())
                .setMobile(mobile)
                .setNickname("用户:" + DesensitizationUtil.commonDisplay(mobile))
                .setImoocNum("用户:" + DesensitizationUtil.commonDisplay(mobile))
                .setFace(Face)
                .setBirthday(DateUtil.stringToDate("2000-01-01"))
                .setSex(Sex.SECRET.type)
                .setCountry("中国")
                .setProvince("")
                .setCity("")
                .setDistrict("")
                .setDescription("这个家伙很懒,什么都没留下~")
                .setCanImoocNumBeUpdated(YesOrNo.YES.type)
                .setUpdatedTime(LocalDateTime.now())
                .setCanImoocNumBeUpdated(1);
        // 插入数据库中
        usersMapper.insert(newUser);
        return newUser;
    }
}




